import React, {useEffect, useRef, useState} from 'react';
import {
    Button,
    Card,
    Form,
    Image,
    Input,
    message,
    Modal,
    Select,
    Space,
    Table,
    Tooltip,
    Typography,
    Upload
} from "antd";
import {
    reqAddShop,reqDeleteShop,
    reqGetShopList,
    reqUpdateShop,
} from "../../../api/backStage/backStageApi";
import {DeleteFilled, EditOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import classes from "../UserHandle/UserTable/index.module.scss";
import axios from "axios";
import {debounce} from "lodash";


//添加商品表单的配置
const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 8,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};

//上传头像的方法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    console.log(reader)
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
};


const AdminShop = () => {

    const [shopListData, setShopListData] = useState([])

    const [deleteOpen, setDeleteOpen] = useState(false);


    //编辑用户
    const [editingShop, setEditingShop] = useState(false);
    const [shopId, setShopId] = useState(null)
    const userFormRef = useRef()
    const [form] = Form.useForm();

    //新增用户的拟态框
    const [modalOpen, setModalOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);

    //上传头像
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState([]);


    useEffect(() => {
        getShopData()
    }, [])
    const getShopData = async () => {
        const result = await reqGetShopList()
        setShopListData(result.data)
    }

    useEffect(() => {
        if (editingShop) {
            form.setFieldsValue({
                cover: imageUrl
            });
        }
    }, [imageUrl])

    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            width: 200,
            render: (_, record) => (
                <Image width={150} src={record.cover}/>
            )
        },
        {
            title: '名称',
            dataIndex: 'shop_name',
            width: 300,
            render: (text) => <a>{text}</a>,
        },
        {
            title: '价格',
            dataIndex: 'price',
            width: 200,
            sorter: {
                compare: (a, b) => a.price - b.price,
                multiple: 999,
            },
            render: text => <span style={{color: '#aaa'}}>{text}</span>
        },
        {
            title: '库存',
            dataIndex: 'num',
            width: 200,
            sorter: {
                compare: (a, b) => a.num - b.num,
                multiple: 1,
            },
        },
        {
            title: '运费',
            dataIndex: 'freight',
            width: 200,
        },
        {
            title: '操作',
            dataIndex: 'handle',
            width: 200,
            render: (_, record) => {
                return (
                    <Typography.Link>
                        <Space size="large">
                            <Tooltip title="修改">
                                <Button onClick={() => updateShop(record)} type="primary">
                                    <EditOutlined/>
                                </Button>
                            </Tooltip>
                            <Tooltip title="删除">
                                <Button onClick={() => {
                                    setDeleteOpen(true)
                                    setShopId(record.id)
                                }} type="primary" danger>
                                    <DeleteFilled/>
                                </Button>
                            </Tooltip>
                        </Space>
                    </Typography.Link>
                );
            },
        },
    ];

    const addShop = () => {
        form.resetFields()
        setImageUrl(null)
        setEditingShop(false)
        setModalOpen(true)
    }


    const addAndUpdateHandleOk = async () => {
        if (editingShop) {
            try {
                const fd = {
                    ...form.getFieldValue(),
                    cover: imageUrl
                }
                setConfirmLoading(true);
                const result = await reqUpdateShop({shop_id: shopId, fd})
                if (result.status === 0) {
                    setTimeout(async () => {
                        setModalOpen(false);
                        setConfirmLoading(false);
                        message.success('修改商品成功!')
                        getShopData()
                    }, 1000);
                } else {
                    message.error('修改失败!')
                }
            } catch (err) {
                message.error(err)
            }
        } else {
            try {
                setConfirmLoading(true);
                const fd = form.getFieldValue()
                const result = await reqAddShop({fd})
                if (result.status === 0) {
                    setTimeout(async () => {
                        setModalOpen(false);
                        setConfirmLoading(false);
                        message.success('添加商品成功!')
                        getShopData()
                    }, 1000);
                } else {
                    message.error('添加失败!')
                }
            } catch (err) {
                message.error(err)
            }
        }
    };
    const addHandleCancel = () => {
        setModalOpen(false);
        setConfirmLoading(false)
    };

    const updateShop = (record) => {
        setEditingShop(true)
        setModalOpen(true)
        setShopId(record.id)
        setImageUrl([record.cover])
        if (form) {
            form.setFieldsValue({
                ...record,
                cover: imageUrl
            })
        }
    }

    //搜索
    const searchShop = debounce(async (e) => {
        const result = await reqGetShopList()
        setShopListData(result.data.filter((item) => item.shop_name.indexOf(e.target.value) !== -1))
    }, 500)

    //删除操作成功
    const deleteShopOk = async () => {
        try {
            setConfirmLoading(true);
            const result= await reqDeleteShop({shop_id:shopId})
            if (result.status===0){
                setTimeout(async () => {
                    await getShopData()
                    setDeleteOpen(false);
                    setConfirmLoading(false);
                    message.success('删除商品成功!')
                }, 1000);
            }
        } catch (err) {
            message.error('删除商品失败！')
        }
    };
    const deleteShopCancel = () => {
        setDeleteOpen(false);
    };

    const onChange = (pagination, filters, sorter, extra) => {
        console.log(pagination, filters, sorter, extra);
    };

    //自定义上传
    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/admin/shop-page/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            const error = new Error("Some error");
            onError(err);
        }
    }
    //上传组件选择图片的事件
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            console.log(info)
            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                setImageUrl([url]);
            });
        }
    };
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8,}}></div>
        </div>
    )
    const searchRef = useRef()

    return (
        <div>
            <Card>
                <div style={{display: 'flex', justifyContent: 'space-between'}}>
                    <Button onClick={() => addShop()} type="primary" style={{marginBottom: 15}}>新增+</Button>
                    <Form ref={searchRef} style={{display: 'flex'}} name="chooseForm">
                        <Space>
                            <Form.Item name="search">
                                <Input.Search onChange={searchShop} placeholder="根据商品名称搜索"/>
                            </Form.Item>
                            <Form.Item>
                                <Button onClick={() => {
                                    getShopData()
                                    searchRef.current.resetFields()
                                }}>重置</Button>
                            </Form.Item>
                        </Space>
                    </Form>
                    <Modal
                        width={800}
                        title={editingShop ? "编辑商品" : "新增商品"}
                        open={modalOpen}
                        onCancel={addHandleCancel}
                        footer={null}
                    >
                        <Form
                            {...formItemLayout}
                            ref={userFormRef}
                            form={form}
                            name="add"
                            onFinish={addAndUpdateHandleOk}
                            style={{maxWidth: 600}}
                            scrollToFirstError
                        >
                            <Form.Item
                                name="shop_name"
                                label="商品名称"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入商品名称!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="price"
                                label="价格"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入运费!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>


                            <Form.Item
                                name="num"
                                label="库存"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入库存!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="freight"
                                label="运费"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入运费!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="cover"
                                label="封面"
                                rules={[
                                    {
                                        required: true,
                                        message: '请上传封面!',
                                    },
                                ]}
                                getValueFromEvent={normFile}
                                valuePropName="fileList">

                                <Upload
                                    listType="picture-card"
                                    showUploadList={false}
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                    maxCount={1}
                                    customRequest={customRequest}
                             
                                >
                                    {imageUrl ? (
                                        <img
                                            src={imageUrl}
                                            alt="avatar"
                                            style={{width: '100%'}}
                                        />
                                    ) : (uploadButton)}
                                </Upload>
                            </Form.Item>


                            <div className={classes.FooterBtn}>
                                <div>
                                    <Form.Item>
                                        <Button type="primary">
                                            重置表单
                                        </Button>
                                    </Form.Item>
                                </div>
                                <div style={{display: 'flex'}}>
                                    <Space>
                                        <Form.Item>
                                            <Button onClick={() => setModalOpen(false)}>
                                                取消
                                            </Button>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button type="primary" htmlType="submit" loading={confirmLoading}>
                                                {editingShop ? "确认修改" : "确认添加"}
                                            </Button>
                                        </Form.Item>
                                    </Space>
                                </div>
                            </div>
                        </Form>
                    </Modal>
                </div>
                <Table
                    rowKey={record => record.id}
                    scroll={{y: 600}}
                    columns={columns}
                    dataSource={shopListData}
                    onChange={onChange}
                />
            </Card>
            <Modal
                centered
                title="确认删除所选项吗？"
                open={deleteOpen}
                onOk={deleteShopOk}
                okText="确认删除"
                cancelText="取消"
                confirmLoading={confirmLoading}
                onCancel={deleteShopCancel}
            >
                <p>删除之后不可恢复！</p>
            </Modal>
        </div>
    );
};

export default AdminShop;